package com.yvon.maple.utils;

import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.Arrays;

/**
 * IP帮助工具
 * @author FrozenWatermelon
 */
@Slf4j
public class IpHelper {
    private static final String UNKNOWN = "unknown";
    private static final String IPV6_LOCAL_IP = "0:0:0:0:0:0:0:1";

    /**
     * 得到用户的真实地址,如果有多个就取第一个
     *
     * @return
     */
    public static String getIpAddr() {
        if (RequestContextHolder.getRequestAttributes() == null) {
            return "";
        }
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

        String ip = null;

        // 1. 优先从代理头获取 IP（按优先级检查）
        String[] headers = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_CLIENT_IP",
                "HTTP_X_FORWARDED_FOR"
        };

        for (String header : headers) {
            ip = request.getHeader(header);
            if (ip != null && !ip.isEmpty() && !UNKNOWN.equalsIgnoreCase(ip)) {
                break;
            }
        }

        // 2. 若代理头为空，使用 RemoteAddr
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 3. 处理 X-Forwarded-For 多 IP 情况（取第一个非 unknown 的 IP）
        if (ip != null && ip.contains(StrUtil.COMMA)) {
            ip = Arrays.stream(ip.split(StrUtil.COMMA))
                    .map(String::trim)
                    .filter(subIp -> !UNKNOWN.equalsIgnoreCase(subIp))
                    .findFirst()
                    .orElse(ip);
        }

        // 4. 本地 IP 处理（开发环境）
        if (Ipv4Util.LOCAL_IP.equals(ip) || IPV6_LOCAL_IP.equals(ip)) {
            try {
                InetAddress inet = InetAddress.getLocalHost();
                ip = inet.getHostAddress();
            } catch (Exception e) {
                log.error("获取本地 IP 失败: ", e);
            }
        }

        return ip;
    }


}
